package com.dcsgo.socketPlay.client;

import com.dcsgo.socketPlay.client.game.Game;
import com.dcsgo.socketPlay.client.game.GamePanel;
import com.dcsgo.socketPlay.common.Message;
import com.dcsgo.socketPlay.common.MessageType;

import java.io.IOException;

/**
 * @author DCSGO
 * @version 1.0
 * 客户端连接服务端的线程类
 */
public class ClientConnectServerThread extends Thread {
    private static boolean loop = true;

    @Override
    public void run() {
        try {
            Services.load();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        Game.playGame();
        System.out.println("ClientConnectServerThread开始执行了");
        while (loop) {
            try {
                Message receiveMes = Services.receiveMessage();
                if (receiveMes == null) {
                    continue;
                }
                //更新Balls
                if (receiveMes.getMesType().equals(MessageType.RENEW_BALLS)) {
                    GamePanel.setBalls(receiveMes.getBallList());
                    GamePanel.setReplaceBall(receiveMes.getReplaceBall());

                } else if (receiveMes.getMesType().equals(MessageType.CLIENT_OFFLINE)) {
                    loop = false;
                    Services.offline();
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public static void shutdown() {
        loop = false;
    }

    public boolean isLoop() {
        return loop;
    }
}
